<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索框 -->
      <el-row :gutter="15">
        <el-col :span="10">
          <el-input
            v-model="queryInfo.query"
            placeholder="请输入内容"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            />
          </el-input>
        </el-col>
        <!-- 添加用户按钮 -->
        <el-col :span="4">
          <el-button
            type="primary"
            @click="addDialogVisible = true"
          >添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table
        :data="userlist"
        border
        stripe
      >
        <el-table-column type="index" />
        <el-table-column
          label="用户名"
          prop="nickName"
        />
        <el-table-column
          label="账号"
          prop="account"
        />
        <!-- <el-table-column
          label="电话"
          prop="mobile"
        />
        <el-table-column
          label="角色"
          prop="role_name"
        /> -->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStatuChanged(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180px"
        >
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-tooltip
              effect="dark"
              content="编辑"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="UserEditDialog(scope.row)"
              />
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUserId(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <!-- <el-pagination
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      /> -->
    </el-card>
    <!-- 添加用户对话框区域 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      center
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        ref="addUserRef"
        :model="addUser"
        :rules="addUserRules"
        label-width="80px"
      >
        <el-form-item
          label="用户名"
          prop="nickName"
        >
          <el-input v-model="addUser.nickName" />
        </el-form-item>
        <el-form-item
          label="登录账号"
          prop="account"
        >
          <el-input v-model="addUser.account" />
        </el-form-item>
        <el-form-item
          label="密码"
          prop="newPassword"
        >
          <el-input
            v-model="addUser.newPassword"
            type="password"
          />
        </el-form-item>
        <el-form-item
          label="确认密码"
          prop="confirmPassword"
        >
          <el-input
            v-model="addUser.confirmPassword"
            type="password"
          />
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addUserCheck"
        >确 定</el-button>

      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="EditDialogVisible"
      width="50%"
      center
      @close="EditDialogClosed"
    >
      <el-form
        ref="EditFormRef"
        :model="EditForm"
        :rules="EditFormRules"
        label-width="80px"
      >
        <el-form-item
          label="账号"
          prop="account"
        >
          <el-input
            v-model="EditForm.account"
            disabled
          />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input
            v-model="EditForm.nickName"
          />
        </el-form-item>
        <el-form-item
          label="旧密码"
          prop="oldPassword"
        >
          <el-input
            v-model="EditForm.oldPassword"
            type="password"
          />
        </el-form-item>
        <el-form-item
          label="新密码"
          prop="newPassword"
        >
          <el-input
            v-model="EditForm.newPassword"
            type="password"
          />
        </el-form-item>
        <el-form-item
          label="确认密码"
          prop="confirmPassword"
        >
          <el-input
            v-model="EditForm.confirmPassword"
            type="password"
          />
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="EditDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="EditUserInfo"
        >确 定</el-button>

      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getAllUser, modifyUserInfo, addUser, delUser } from '@/api/user'
export default {
  data() {
    /* 验证确认密码的规则 */
    var addPasswordCheck = (rule, value, callback) => {
      if (value !== this.addUser.newPassword) {
        return callback(new Error('两次输入密码不一致!'))
      } else {
        return callback()
      }
    }
    var editPasswordCheck = (rule, value, callback) => {
      if (value !== this.EditForm.newPassword) {
        return callback(new Error('两次输入密码不一致!'))
      } else {
        return callback()
      }
    }
    return {
      /* 获取数据库用户列表的数据参数 */
      queryInfo: {
        query: '',
        /* 当前页码 */
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      /* 控制添加用户对话框的显示 */
      addDialogVisible: false,
      /* 添加用户的数据 */
      addUser: {
        nickName: '',
        account: '',
        newPassword: '',
        confirmPassword: ''
      },
      /* 添加用户的验证规则 */
      addUserRules: {
        nickName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度应在3-10个字之间', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '密码长度应在6-18个字之间', trigger: 'blur' }
        ],
        account: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 10, message: '账号长度应在3-10个字之间', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { required: true, validator: addPasswordCheck, trigger: 'blur' }
        ]
      },
      /* 控制编辑用户对话框的显示 */
      EditDialogVisible: false,
      /* 返回的用户信息 */
      EditForm: {
        account: '',
        nickName: '',
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      /* 修改用户信息表单的验证规则 */
      EditFormRules: {
        nickName: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
          { min: 6, max: 18, message: '请输入6~18位的密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 18, message: '请输入6~18位的密码', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { required: true, validator: editPasswordCheck, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getUserList()
  },
  methods: {
    /* 获取用户信息 */
    async getUserList() {
      const { data: res } = await getAllUser()
      this.userlist = res
      console.log(res)
    },
    /* 监听handleSizeChange */
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    /* 监听页码值改动 */
    handleCurrentChange(newPage) {
      /* console.log(newPage) */
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    /* 更改用户状态 */
    async userStatuChanged(userInfo) {
      /* console.log(userInfo) */
      const { data: res } = await this.$http.put(`user/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    /* 监听添加用户对话框的关闭 */
    addDialogClosed() {
      this.$refs.addUserRef.resetFields()
    },
    /* 添加用户并验证 */
    addUserCheck() {
      this.$refs.addUserRef.validate(async valid => {
        /* console.log(valid) */
        if (!valid) return
        const res = await addUser(this.addUser)
        if (res.code !== 1) {
          console.log(res)
          /* 关闭对话框 */
          this.addDialogVisible = false
          /* 重新请求用户数据 */
          this.getUserList()
        }
      })
    },
    /* 控制修改用户对话框展开 */
    async UserEditDialog(row) {
      /* console.log(row) */
      this.EditForm = row
      console.log(this.EditForm)
      this.EditDialogVisible = true
    },
    /* 监听修改用户对话框的关闭 */
    EditDialogClosed() {
      this.$refs.EditFormRef.resetFields()
    },
    /* 修改提交用户信息 */
    EditUserInfo() {
      console.log(this.EditForm)
      this.$refs.EditFormRef.validate(async valid => {
        /* console.log(valid) */
        if (!valid) return
        /* 发送请求修改用户信息 */
        const res = await modifyUserInfo(this.EditForm)
        if (res.code !== 0) { return }
        this.$message.success('修改成功')
        this.EditDialogVisible = false
        this.getUserList()
      })
    },
    /* 删除用户 */
    async removeUserId(row) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      /* 若用户确认删除，则返回值为confirm */
      /* 若用户取消删除，则返回值为cancel */
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      const res = await delUser(row)
      console.log(res)
      if (res.code !== 0) {
        return
      }
      this.$message.success('删除用户成功')
      this.getUserList()
    }
  }
}
</script>
<style lang="less" scoped>
</style>
